const API_URL = 'https://free-api.heweather.net/s6/air/now'
const request = require('request')
const $ = {
  // 获空气质量色
  airBackgroundColor: (aqi) => {
    if (aqi < 50) {
      return '#00cf9a'
    } else if (aqi < 100) {
      return '#00cf9a'
    } else if (aqi < 200) {
      return '#4295f4'
    } else if (aqi > 300) {
      return '#ff6600'
    }
  },
}
exports.main = async (event) => {
  let location = event.city
  let params = {
    location,
    key: '3f171da1113f434e9e36367bc4eae603' //和风天气中应用的密钥
  }
  let query = []
  for (let i in params) {
    query.push(`${i}=${encodeURIComponent(params[i])}`)
  }
  let url = API_URL + '?' + query.join('&')
  return new Promise((resolve, reject) => {
    request.get(url, (error, response, body) => {
      if (error || response.statusCode !== 200) {
        reject(error)
      } else {
        try {
          let data = JSON.parse(body)
          if (data && data.HeWeather6 && data.HeWeather6[0].air_now_city) {
            let { aqi, qlty } = data.HeWeather6[0].air_now_city
            resolve({
              status: 0,
              aqi,
              color: $.airBackgroundColor(aqi),
              name: qlty
            })
          } else {
            resolve({
              status: 500
            })
          }
        } catch (e) {
          reject(e)
        }
      }
    })
  })
}
